﻿using System;
using System.Collections.Generic;
using System.Text;
using Model;
using AppToolKit.Core.Context.Spring;
using Common.Logging;
using Utility;
using BLL.Action.Core.Caching;

namespace BLL.Action.Core.State
{
    [AutoWiring]
    public class StateMonitor
    {
        public const string threadCount = "Count";

        public const string threadError = "Error";

        public event EventHandler threadCountEvent;

        public event EventHandler threadErrorEvent;

        ILog log = LogManager.GetLogger(LogDefault.AppDebug);
        [AutoWiring]
        public ClientCache Cache { get; set; }

        public void RunMonitor()
        {
            log.Debug(string.Format("Run monitor"));
            if (threadCountEvent != null)
            {
                List<JobState> state = CacheHelper.Cache(Cache, threadCount, delegate { return GetStateMonitor(); }) as   List<JobState> ;
                log.Debug(string.Format("Run threadCountEvent"));
                threadCountEvent.Invoke(state.Count, new EventArgs());
            }

            if (threadErrorEvent != null)
            {
                List<JobState> state = CacheHelper.Cache(Cache, threadError, delegate { return GetStateMonitor(); }) as  List<JobState> ;
                log.Debug(string.Format("Run threadErrorEvent"));
                threadErrorEvent.Invoke(state.Count, new EventArgs());
            }
        }
        private List<JobState> GetStateMonitor()
        {
            List<JobState> state = new List<JobState>();
            return state;
        }
        public void WirteErrorLog(string hotelid,string msg)
        {
            List<JobState> list = CacheHelper.Cache(Cache, State.StateMonitor.threadError, delegate { return GetStateMonitor(); }) as List<JobState>;

            if (list.Count >50)
                list.Clear();
           
            JobState state = new JobState();
            state.Time = DateTime.Now;
            state.Hotelid = hotelid;
                state.ErrorMsg = msg;
            list.Add(state);

            RunMonitor();
        }
        public void WirteNormalLog(string hotelid, string msg)
        {
            List<JobState> list = CacheHelper.Cache(Cache, State.StateMonitor.threadCount, delegate { return GetStateMonitor(); }) as List<JobState>;

            foreach (JobState state1 in list)
            {
                if (state1.Hotelid == hotelid)
                {
                    list.Remove(state1);
                    break;
                }
            }

            JobState state = new JobState();

            state.Hotelid = hotelid;
            state.Msg = msg;
            state.Time = DateTime.Now;
            list.Add(state);

            RunMonitor();

        }
    }
}
